#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import sys
import os
import dbus
import dbus.service
import dbus.glib
import gobject
from managers.commHAL import *
from managers.agent import *
from managers.vhd import *
from managers.cams import *
import md5
	
class GUIManager(dbus.service.Object):
	def __init__(self, bus_name, agent, object_path="/org/security/agent/gui"):
		dbus.service.Object.__init__(self, bus_name, object_path)
		self.agent = agent
		self.db = agent.getDBManager()
		self.motion = agent.m

	@dbus.service.method("org.security.agent")
	def setMaxSpace(self,space):
		self.agent.setMaxSpace(space)
		return True
		
	@dbus.service.method("org.security.agent")
	def setAdminMail(self,text):
		self.agent.setAdminMail(text)
		return True
		
	@dbus.service.method("org.security.agent")
	def getMaxSpace(self):
		return self.agent.getMaxSpace() 
		
	@dbus.service.method("org.security.agent")
	def getAdminMail(self):
		return self.agent.getAdminMail()
		
	@dbus.service.method("org.security.agent")
	def setMaxDuration(self,segons):
		self.agent.setMaxDuration(segons)
		return True
		
	@dbus.service.method("org.security.agent")
	def getMaxDuration(self):
		return self.agent.getMaxDuration() 
		
	@dbus.service.method("org.security.agent")
	def getCameraList(self):
		print "getCameraList"
		SystemCam.setDisconnect(self.db)
		t={}
		lists = [getCamerasV4L(),getCameras('/proc/video/',t)]
		print "Encontradas: ", lists
		cactivates=[]
		for list in lists:
			for idCamera in list.keys():
				m = md5.new()
				m.update(idCamera)
				id = str(m.hexdigest())
				print "ENTRO AQUI??? QUANTS COPS?!"
					
				if not SystemCam.existsCamera(self.db, id):
					cam = SystemCam(id,'conn',0,30,1,idCamera,0.5,SystemCam.getNewPort(self.db))
					cam.init(self.agent)
				else:
					cam = SystemCam.getFromId(self.db, id)
					cam.tipus = 'conn'
					cam.save(self.agent)

		list = []
		for cam in SystemCam.getConnected(self.db):
			list.append(cam.getContent())
		return dbus.Array(list,dbus.Variant)

	@dbus.service.method("org.security.agent")
	def getCameraURL(self,idCamera):
		try:
			port = get_port(idCamera)
			ip = os.popen('/sbin/ifconfig eth0 |grep inet').read()[20:35].spli(' ')[0]
			return "http://" + ip + ":" + str(port)
		except:
			print 'gui::getCameraURL error!'
			return -1

	@dbus.service.method("org.security.agent")
	def viewRecord(self,id_record):
		return self.db.query("select Path from Records WHERE id = " + id_record)

	@dbus.service.method("org.security.agent")
	def iniRecord(self,idCamera):
		try:
			ini_record(idCamera)
			return True
		except:
			print 'gui::iniRecord error!'
			return False

	@dbus.service.method("org.security.agent")
	def stopRecord(self,idCamera): 
		try:
			stop_record(idCamera)
			return True
		except:
			print 'gui::iniRecord error!'
			return False

	@dbus.service.method("org.security.agent")
	def removeMovie(self,idRecord):
		file = self.db.query("SELECT Path FROM Records WHERE id=" + idRecord)
		try:
			os.system("rm " + file[0])
			self.db.query("UPDATE Records SET Deleted=1 WHERE id=" + idRecord)
			return True
		except:
			return False
		
	@dbus.service.method("org.security.agent")
	def reviewMovie(self,idRecord):
		self.db.query("UPDATE Records SET Review=1 WHERE id=" + idRecord)
		return True

	@dbus.service.method("org.security.agent")
	def protectMovie(self,idRecord):
		self.db.query("UPDATE Records SET Protected=1 WHERE id=" + idRecord)

	@dbus.service.method("org.security.agent")
	def queryMovies(self, firstDate, init, length, protected, reviewed, started):
		where = []
		if protected>=0:
			where.append("Protected=%d"%(protected))
		if reviewed>=0:
			where.append("Review=%d"%(reviewed))
		if started!='t':
			where.append("Started='%c'"%(started))
		where.append("Init <= %d"%(firstDate))
		tmp = " AND "
		cond = tmp.join(where)
		query = "SELECT * FROM Records WHERE %s LIMIT %d,%d"%(cond,init,length) 
		res = self.db.query(query)
		return dbus.Array(res, dbus.Variant)

	@dbus.service.method("org.security.agent")
	def setCamProperties(self, camid, enabled, fps, mode, nom, threshold):
		c = SystemCam.getFromId(self.db, camid)
		c.camid = camid
		c.enabled = enabled
		c.fps = fps
		c.mode = mode
		c.nom = nom
		c.threshold = threshold
		c.save(self.agent)
		c.configure(self.agent)
		#c.init(self.agent)

	@dbus.service.method("org.security.agent")
	def getCamProperties(self, idcam):
		return SystemCam.getFromId(self.db, idcam).getContent()
